export default {
    state: {
		//购物车的所有商品
        items: [],
		//列表直接添加的简单商品，用于列表显示
		simple_items:[],
    },
    getters: {
		shopCartTotal: state => {
			let total = {
				money: 0,
				quantity: 0,
			};
			state.items.forEach(item => {
				total.quantity += parseInt(item.quantity);
				total.money += parseFloat(item.total_price);
			})
			return total;
		}
    },
    mutations: {
		//加入购物车
		productAddCart(state, product) {
			let data = {
				id: product.id,
				name: product.name,
				price: product.price,
				total_price: 0,
				quantity: 1,
				prop_id: [],
				prop_text: '',
			};
			
			//加子商品价格
			let prop_id = [];
			let prop_text = [];
			let total_price = parseFloat(product.price);
			product.children.forEach((cate, index1) => {
				cate.children.forEach((item, index2) => {
					if (item.selected === true) {
						total_price += parseFloat(item.price);
						prop_id.push(item.id);
						prop_text.push(item.name + item.price + '元');
					}
				})
			})
			data.prop_id = prop_id;
			data.prop_text = prop_text.join(',');
			data.total_price = parseFloat(total_price);

			
			//检查购物是否存在相同的商品
			let isRepeat = false;
			state.items.forEach((item,index) => {
				if (item.id === data.id && item.prop_text === data.prop_text) {
					state.items[index].quantity += 1;
					state.items[index].total_price += parseFloat(data.total_price);
					isRepeat = true;
				}
			});
			
			if (!product.children.length) {
				if (state.simple_items[product.id]) {
					state.simple_items[product.id]++
				} else {
					state.simple_items[product.id] = 1;
				}
			}
			
			if (!isRepeat) {
				state.items.push(data);
			}
		},
		//清空购物车
		productEmptyCart(state){
			state.items = [];
			state.simple_items = [];
		},
		//减少-购物车中商品的数量
		subQuantity(state, data){
			state.items.forEach((item,index) => {
				if (item.id == data.id && item.prop_text == data.prop_text && data.quantity >= 1) {
					state.items[index].total_price -= data.total_price / data.quantity;
					state.items[index].quantity -= 1;
					//如果商品数量小于0后删除
					if (state.items[index].quantity<=0) {
						state.items.splice(index,1);
					}
				}
			});
			if (!data.children) {
				if (state.simple_items[data.id]>=1) {
					state.simple_items[data.id]--
				} else {
					state.simple_items[data.id] = 0;
				}
			}
		},
		//增加-购物车中商品的数量
		addQuantity(state, data){
			state.items.forEach((item,index) => {
				if (item.id == data.id && item.prop_text == data.prop_text && data.quantity >= 1) {
					state.items[index].total_price += data.total_price / data.quantity;
					state.items[index].quantity += 1;
				}
			});
			
			if (!data.children) {
				state.simple_items[data.id]++
			}
		},
    },
    actions: { 

    }
}